import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_html/flutter_html.dart';
// import 'package:webview_flutter/webview_flutter.dart';
import 'dart:convert';

// 应用的入口
void main() {
  runApp(const MyApp());
}

// 应用的根Widget
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // MaterialApp是一个方便的Widget，它封装了常用的material设计元素
    return MaterialApp(
      title: 'Flutter Bottom Navigation Bar',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '凡可赛：福州大学竞赛信息发布平台'),
    );
  }
}

// 一个带状态的首页Widget
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

// MyHomePage的状态类
class _MyHomePageState extends State<MyHomePage> {

  int _selectedIndex = 0; // 当前选中的索引

  // 选项的Widget列表
  static final List<Widget> _widgetOptions = <Widget>[
    // const Text('首页'),
    const HomePage(),
    const Text('竞赛种类'),
    const Text('福州大学'),
    const Text('我的'),
  ];

  // 当底部导航栏项被点击时调用
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index; // 更新选中的索引，重建UI
    });
  }


  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // 显示当前选中项的内容
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.emoji_events),
            label: '竞赛种类',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: '福州大学',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.black, // 设置选中项目的颜色为黑色
        unselectedItemColor: Colors.grey, // 设置未选中项目的颜色也为黑色
        showUnselectedLabels: true,  // 确保未选中的图标也显示标签
        onTap: _onItemTapped,
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  Future<String> fetchPageContent() async {
    final response = await http.get(
      Uri.parse('https://fancycup.snakontech.com/wp-json/wp/v2/pages/1035'), // 使用您的页面ID
    );

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      return data['content']['rendered'];
    } else {
      throw Exception('Failed to load page');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: fetchPageContent(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        } else if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        } else {
          return SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Html(
                data: snapshot.data ?? '',
              ),
            ),
          );
        }
      },
    );
  }
}

// class HomePage extends StatelessWidget {
//   const HomePage({super.key});

//   @override
//   Widget build(BuildContext context) {
//     return WebView(
//       initialUrl: 'https://fancycup.snakontech.com',
//       javascriptMode: JavascriptMode.unrestricted,
//     );
//   }
// }